package com.chain.BrotherExchange.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.annotation.StringRes;
import android.telephony.TelephonyManager;
import android.text.InputType;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.chain.BrotherExchange.App;
import com.chain.BrotherExchange.R;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import static android.content.Context.TELEPHONY_SERVICE;
import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TASK;

/**
 * Android 工具类
 */
public final class Androids {
    private Androids() {
    }

    private static long mFirstTime;

    public static boolean doubleClickClose(@StringRes int stringRes) {
        long secondTime = System.currentTimeMillis();
        if (secondTime - mFirstTime > 2000) {
            Androids.makeText(stringRes);
            mFirstTime = secondTime;
            return false;
        }

        return true;
    }

    private static Toast mToast;

    @SuppressLint("ShowToast")
    public static void makeText(CharSequence message) {
        if (mToast == null) {
            mToast = Toast.makeText(App.getInstance(), message, Toast.LENGTH_SHORT);
            //mToast.setGravity(Gravity.CENTER, 0, 0);
        } else {
            mToast.setText(message);
        }

        mToast.show();
        Log.d("Androids", "message:" + message);
    }

    public static void makeText(@StringRes int stringRes) {
        makeText(App.getInstance().getResources().getString(stringRes));
    }

    public static String toBase64(ImageView imageView) {
        Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bos);//参数100表示不压缩
        byte[] bytes = bos.toByteArray();
        return "data:image/jpeg;base64," + Base64.encodeToString(bytes, Base64.DEFAULT);
    }

    /**
     * 显示有进度条消息
     */
    private static ProgressDialog mProgressDialog;

    public static void showProgressMessage(Context context, CharSequence message) {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            return;
        }
        mProgressDialog = ProgressDialog.show(context, null, message);
    }

    public static void showProgressMessage(Context context, @StringRes int stringRes) {
        showProgressMessage(context, App.getInstance().getResources().getString(stringRes));
    }

    /**
     * 取消进度条消息
     */
    public static void dismissProgressMessage() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }

    /**
     * 复制到剪切板
     */
    public static void copyToChipBoard(Context context, String content) {
        ClipboardManager cm = (ClipboardManager) context.getApplicationContext()
                .getSystemService(Context.CLIPBOARD_SERVICE);
        assert cm != null;
        cm.setPrimaryClip(ClipData.newPlainText(null, content));
        Androids.makeText(R.string.copy_success);
    }

    /**
     * 获取设置唯一ID
     */
    @SuppressLint("MissingPermission")
    public static String getDeviceID() {
        TelephonyManager TelephonyMgr = (TelephonyManager) App.getInstance()
                .getApplicationContext().getSystemService(TELEPHONY_SERVICE);
        return TelephonyMgr.getDeviceId();
    }

    /**
     * 获取高性能Map
     */
    public static <K, V> Map<K, V> getMap() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            return new ArrayMap<>();
        } else {
            return new HashMap<>();
        }
    }

    /**
     * 获取版本名称
     */
    public static String getVersionName(Context context) {
        String verName = "";
        try {
            verName = context.getPackageManager().
                    getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return verName;
    }

    public static void changePasswordVisibility(CheckBox checkBox, EditText editText) {
        checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            editText.setInputType(isChecked
                    ? InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
                    : InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            editText.setSelection(editText.getText().toString().length());
        });
    }

    /**
     * URI 转 File
     */
    public static File uriToFile(Activity activity, Uri uri) {
        String[] image = {MediaStore.Images.Media.DATA};
        Cursor cursor = activity.managedQuery(uri, image, null, null, null);
        int actualImageColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String imgPath = cursor.getString(actualImageColumnIndex);
        return new File(imgPath);
    }

    /**
     * 隐藏键盘
     */
    public static void hiddenSoftInputFromWindow(Context context, EditText editText) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(
                Context.INPUT_METHOD_SERVICE);
        assert imm != null;
        imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
        editText.setFocusable(false);
        editText.setFocusableInTouchMode(false);
    }

    /**
     * 显示键盘
     */
    public static void showSoftInputFromWindow(Context context, EditText editText) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        assert imm != null;
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
    }

    /**
     * 延时显示键盘
     */
    public static void showDelaySoftInputFromWindow(Context context, EditText editText, long delay) {
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                showSoftInputFromWindow(context, editText);
            }
        }, delay);
    }

    /**
     * 语言
     */
    public static void alertLanguage(Activity activity, String targetLanguage) {
        Locale locale = ("zh-en".equals(targetLanguage)) ? Locale.ENGLISH : Locale.SIMPLIFIED_CHINESE;
        Resources resources = activity.getResources();
        DisplayMetrics displayMetrics = resources.getDisplayMetrics();
        Configuration configuration = resources.getConfiguration();
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){
            configuration.setLocale(locale);
        } else {
            configuration.locale = locale;
        }

        resources.updateConfiguration(configuration, displayMetrics);
    }

    /**
     * 应用本地配置
     */
    public static class LocalConfig {
        public static final String NAME = "configs";
        private static final SharedPreferences mSp = App.getInstance().getSharedPreferences(
                NAME, Context.MODE_PRIVATE);

        private static final String TOKEN = "1";

        // 是否设置交易密码
        private static final String TRANSACTION_PASSWORD_STATE = "2";

        private static final String UID = "3";

        // 注册区号
        private static final String REGION = "4";

        // 拒绝更新版本
        private static final String REFUSED_UPDATE_VERSION = "6";

        // 第一次进入
        private static final String FIRST_ENTER = "7";

        // 用户资产是滞可见
        private static final String USER_ASSETS_VISIBILITY = "8";

        private static final String PHONE = "9";

        // 语言
        private static final String LANGUAGE = "10";

        public static void login(String token, int uid, String phone, String country) {
            mSp.edit().putString(TOKEN, token)
                    .putInt(UID, uid)
                    .putString(PHONE, phone)
                    .putString(REGION, country)
                    .apply();
        }

        public static void logout() {
            mSp.edit().remove(TOKEN)
                    .remove(UID)
                    .remove(PHONE)
                    .remove(REGION)
                    .remove(TRANSACTION_PASSWORD_STATE)
                    .apply();
        }

        /**
         * 设置交易密码
         */
        public static void setAlreadySetTransactionPassword(boolean state) {
            mSp.edit().putBoolean(TRANSACTION_PASSWORD_STATE, state).apply();
        }

        public static void setUserAssetsVisibility(boolean visibility) {
            mSp.edit().putBoolean(USER_ASSETS_VISIBILITY, visibility).apply();
        }

        public static boolean getUserAssetsVisibility() {
            return mSp.getBoolean(USER_ASSETS_VISIBILITY, false);
        }

        public static String getToken() {
            return mSp.getString(TOKEN, null);
        }

        public static int getUid() {
            return mSp.getInt(UID, 0);
        }

        public static String getPhone() {
            return mSp.getString(PHONE, "");
        }

        public static String getRegion() {
            return mSp.getString(REGION, null);
        }

        public static void refusedUpdateVersion(float version) {
            mSp.edit().putFloat(REFUSED_UPDATE_VERSION, version).apply();
        }

        public static float getRefusedVersion() {
            return mSp.getFloat(REFUSED_UPDATE_VERSION, 0);
        }

        /**
         * 是否登录
         */
        public static boolean isLogin() {
            return !TextUtils.isEmpty(getToken());
        }

        /**
         * 是否设置交易密码
         */
        public static boolean isSetTransactionPassword() {
            return mSp.getBoolean(TRANSACTION_PASSWORD_STATE, false);
        }

        public static boolean isFirstEnter() {
            return !getVersionName(App.getInstance()).equals(mSp.getString(FIRST_ENTER, ""));
        }

        public static void setFirsEnterInfo() {
            mSp.edit().putString(FIRST_ENTER, getVersionName(App.getInstance())).apply();
        }

        public static String getLanguage() {
            return mSp.getString(LANGUAGE, "zh-cn");
        }

        public static void alterLanguage() {
            mSp.edit().putString(LANGUAGE, getLanguage().equals("zh-cn") ? "zh-en" : "zh-cn").apply();
        }
    }
}
